<?php

/**
 * Created by PhpStorm.
 * User: yh
 * Date: 2017/6/6
 * Time: 11:19
 */
class Address extends Web_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Zone_model', 'zone_model');//编码信息
        $this->load->model('Address_model', 'address_model');//收货地址表
        $this->load->model('User_model', 'user_model');//user表
        $this->load->helper(array('time', 'url'));//时间工具类
    }

    public function index()
    {   

        $this->getAllAddressByUid();
    } 

    //添加收货地址
    public function add()
    {
        $this->addAddress();
    }

    //编辑
    public function edit($address_id = null)
    {
        $this->updateAddressById($address_id);
    }

    //删除
    public function del($address_id = null)
    {
        $this->delAddressById($address_id);
    }

    //管理用户收货地址
    function getAllAddressByUid()
    {
        $user = $this->userSession(true, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        //$user = (object)array('uid' => '1');
        $uid = $user->uid;
        $address = $this->address_model->getAddressByUid($uid);
        $data['base_url'] = $this->config->item('base_url');
        for ($i = 0; $i < count($address); $i++)
        {
            //省
            $address[$i]['province_text'] = $this->zone_model->getZonesById($address[$i]['province'])['name'];
            //城市
            $address[$i]['city_text'] = $this->zone_model->getZonesById($address[$i]['city'])['name'];
            //地区
            $address[$i]['district_text'] = !empty($this->zone_model->getZonesById($address[$i]['district']))?$this->zone_model->getZonesById($address[$i]['district'])['name']:"";
            // 手机号码
            //收货人
            //详细地址
            //是否是默认
            $users = $this->user_model->getUserByUid($uid);
            // $address[$i]['address_id1'] = $users['address_id'];//默认地址ID
            $address[$i]['default'] = $address[$i]['address_id'] === $users['address_id'] ? true : false;
            //创建时间
            $address[$i]['create_time'] = _gettimestr($address[$i]['create_time'], 'Y-m-d H:i:s');
            $address[$i]['update_time'] = _gettimestr($address[$i]['update_time'], 'Y-m-d H:i:s');
        }
        $arr =array();
        foreach ($address as $k=>$v)
            $arr[$v['address_id']]= $v;

        $data['content'] = $arr;
        $data['title'] = '收货地址管理';
        $data['uid'] = $uid;
        $data['user'] = $user;
        $data['dataFromGet'] = $this->input->get('data');//从订单填写页进入到管理收货地址页会传
        //echo json_encode($data);
        $this->loadView('header', $data);
        $this->loadView('address_manage', $data);
    }

    // 根据aid获取某一条收货地址
    function getAddressByAid($address_id = null) {
        $address_id = $this->input->get('address_id');
        $info = $this->address_model->getAddressByAid($address_id);
        if (!empty($info))
        {
            $this->response(array('result' => 0,'errmsg' => $info));
        }
        else
        {
            $this->response(array('result' => 1,'errmsg' => '错误!'));
        }
    }

    //添加收货地址
    function addAddress()
    {
        $user = $this->userSession(true, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        //$user = (object)array('uid' => '1');
        $uid = $user->uid;
        if ($_POST)
        {
            $address_alias = '家';
            $consignee = $this->input->post('consignee');
            $mobile = $this->input->post('mobile');
            $province = $this->input->post('provinceid');
            $city = $this->input->post('cityid');
            $district = $this->input->post('districtid');
            $address = $this->input->post('address');
            $data = array(
                'uid' => $uid,
                'address_alias' => $address_alias,
                'country' => '0',
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'address' => $address,
                'consignee' => $consignee,
                'mobile' => $mobile,
                'create_time' => _gettime(),
                'update_time' => _gettime()
            );
            $address = $this->address_model->getAddressByUid($uid);
            $did = $this->address_model->addAddress($data);
            if(empty($address))
            {
                //如果当前是第一次设置 默认为默认地址
                $this->user_model->setAddressid($uid, $did);
            }
            if ($did != 0)
            {
                // 返回列表页
                //redirect('home/address');
                echo json_encode(array('result'=>'0'));
                return;
            }
            else
            {
                $data['errmsg'] = '添加失败';
                echo json_encode(array('result' => 1, 'errmsg' => '添加失败'));
                return;
            }
        }
        $data['base_url'] = $this->config->item('base_url');
        $data['title'] = '添加新地址';
        $data['dataFromGet'] = $this->input->get('data');//从订单填写页进入到管理收货地址页会传
        $this->loadView('header', $data);
        $this->loadView('address_add.php');
    }


    //修改收货地址
    function updateAddressById($address_id = null)
    {
        $user = $this->userSession(true, 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        //$user = (object)array('uid' => '1');
        $uid = $user->uid;
        if ($_POST)
        {
            $consignee = $this->input->post('consignee');
            $mobile = $this->input->post('mobile');
            $province = $this->input->post('provinceid');
            $city = $this->input->post('cityid');
            $district = $this->input->post('districtid');
            $address = $this->input->post('address');
            $data = array(
                'uid' => $uid,
                'consignee' =>$consignee,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'address' => $address,
                'mobile' => $mobile,
                'update_time' => _gettime()
            );
            $did = $this->address_model->updateAddressById($address_id, $data);
            if ($did != 0)
            {
                // 返回列表页
                echo json_encode(array('result'=>'0'));
                return;
            }
            else
            {
                //array('result' => 1, 'errmsg' => '账号或密码错误')
                $data['errmsg'] = '修改失败';
                echo json_encode(array('result' => 1, 'errmsg' => '修改失败'));
            }
        }
        $content = $this->address_model->getAddressByAid($address_id);
        if(empty($content) || $user->uid !=$content['uid'])
        {
            header('Location:'.$this->base_url.'home/address');return;
        }
        //省
        $content['provincetxt'] = $this->zone_model->getZonesById($content['province'])['name'];
        //城市
        $content['citytxt'] = $this->zone_model->getZonesById($content['city'])['name'];
        //地区
        $content['districttxt'] = ! empty($content['district']) ? $this->zone_model->getZonesById($content['district'])['name'] : '';
        $data['content'] = $content;
        $data['base_url'] = $this->config->item('base_url');
        $data['title'] = '地址详情';
        $data['dataFromGet'] = $this->input->get('data');//从订单填写页进入到管理收货地址页会传
//        echo json_encode($content);
        $this->loadView('header', $data);
        $this->loadView('address_update.php');
    }


    //删除收货地址
    function delAddressById($address_id = 0)
    {
        $user = $this->userSession(false);
        $uid = $user->uid;

        $address_id = $this->input->post('address_id');

        $info = $this->address_model->getAddressByAid($address_id);

        if (!empty($info))
        {
            $res = $this->address_model->delAddressById($address_id, $uid);
            if ($res > 0)
            {
                //如果删除的是默认地址需要重新设置默认地址
                $users = $this->user_model->getUserByUid($uid);
                $defult = $address_id === $users['address_id'] ? true : false;
                $address = $this->address_model->getAddressByUid($uid);
                if (!empty($address))
                {
                    if ($defult)
                    {
                        $this->user_model->setAddressid($uid, $address[0]['address_id']);
                    }
                }
                //redirect('home/address');
                echo json_encode(array('result' => 0));
                return;
            }
            else
            {
                echo json_encode(array('result' => 1,'errmsg' => '删除失败!'));
            }
        }
        else
        {
            echo json_encode(array('result' => 2,'errmsg' => '修改失败!'));
        }
    }
    //获取所有的省份
    public function getZonesByID()
    {
        $zoneid = $this->input->get('zoneid');
        $data = $this->zone_model->getZonesByType($zoneid);
        echo json_encode($data);
    }
    //获取节点下所有城市和地区
    public function getZonesByParentID()
    {
        $zoneid = $this->input->get('zoneid');
        $data = $this->zone_model->getZonesByParentId($zoneid);
        echo json_encode($data);
    }


    //  api   修改收货地址
    function updateAddress($address_id = null)
    {
        $user = $this->userSession(false);
        if(empty($user))
        {
            $this->response(array('result' => 2, 'errmsg' => '请先登录'));
        }
        $uid = $user->uid;
        if ($_POST)
        {
            $address_id = $this->input->post('address_id');

            $consignee = $this->input->post('consignee');
            $mobile = $this->input->post('mobile');
            $province = $this->input->post('provinceid');
            $city = $this->input->post('cityid');
            $district = $this->input->post('districtid');
            $address = $this->input->post('address');
            $data = array(
                'uid' => $uid,
                'consignee' =>$consignee,
                'province' => $province,
                'city' => $city,
                'district' => $district,
                'address' => $address,
                'mobile' => $mobile,
                'update_time' => _gettime()
            );
            $did = $this->address_model->updateAddressById($address_id, $data);
            if ($did != 0)
            {
                $this->response(array('result'=>'0'));
            }
            else
            {
                $this->response(array('result' => 1, 'errmsg' => '修改失败'));
            }
        }

    }
}